package com.j1903.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.j1903.annotation.PassJwt;
import com.j1903.util.JwtUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

public class JwtInterceptor implements
        HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //获取token
        String token=request.getHeader("token");
        if(token!=null){
            String id=JwtUtil.getClaim(token, "id").asString();
            String param=JwtUtil.getClaim(token, "param")
                    .asString();
            System.out.println("id"+id);
            System.out.println("param"+param);
            request.setAttribute("id",id);
            ObjectMapper om=new ObjectMapper();
            Map<String,Object> p=
                    om.readValue(param,Map.class);
            request.setAttribute("tokenParam", p);
        }
        String servletPath=request.getServletPath();
        System.out.println(servletPath);
        //判断是否是自定义控制器的方法
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method=handlerMethod.getMethod();
        //判断当前访问的控制器方法有没有PassJwt注解
        if(method.isAnnotationPresent(PassJwt.class)){
            PassJwt passJwt=method.getAnnotation(PassJwt.class);
            //如果PassJwt注解的required属性为true就放行
            if(passJwt.required()){
                return true;
            }
        }
        if(servletPath.indexOf("/favicon.ico")!=-1||
                servletPath.indexOf("/error")!=-1){
            System.out.println("白名单:"+servletPath);
            return true;
        }
        DecodedJWT decodedJWT=
                JwtUtil.verifyToken(token, "j1903");
        if(decodedJWT==null){
            throw new Exception("无效的token");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
